<template>
  <!-- 新闻管理 添加新闻 -->
  <div v-loading="loading" element-loading-text="拼命加载中">
    <el-row>
      <!-- 搜索框 -->
      <el-col :span="24">
        <div class="search-wrapper">
          <ul class="search-box">
            <li><span class="filter-name">新闻名称：</span>
              <el-input style="width:150px" v-model="listQuery.newsTitle"></el-input>
            </li>
            <li><span class="filter-name">新闻状态：</span>
              <el-select v-model="listQuery.status" clearable placeholder="请选择新增状态" class="filter-item">
                <el-option label="审批通过" value="0"></el-option>
                <el-option label="审批不通过" value="8"></el-option>
                <el-option label="审批中" value="9"></el-option>
                <el-option label="未提交" value="-1"></el-option>
              </el-select>
            </li>
            <li><span class="filter-name">发布时间段：</span>
              <el-date-picker v-model="listQuery.releaseTime" type="datetimerange" :picker-options="pickerOptions2"
                              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"/>
            </li>
            <li style="padding-left:10px;"><el-button style="vertical-align:middle;margin-top:-2px;" round size="mini" type="primary" @click="getList">查询</el-button></li>
          </ul>
        </div>
      </el-col>
      <!-- 按钮区 -->
      <el-col :span="24">
        <div class="button-wrapper">
          <el-button type="primary" style="vertical-align:middle;margin-top:10px;margin-left: 5px" round size="mini" @click="dialogFormVisible = true">新增</el-button>
          <el-button type="danger" style="vertical-align:middle;margin-top:10px;" round size="mini" @click="batchEdit(-1)">删除</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-col :span="24">
        <div class="data-wrapper">
          <template v-if="tableData!=null">
            <el-table ref="multipleTable" :data="tableData"  tooltip-effect="dark" style="width: 100%"
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection" label="全选" width="55">
              </el-table-column>
              <el-table-column type="index" label="序号" width="55" :index="indexMethod">
              </el-table-column>
              <el-table-column prop="newsNum" label="新闻编号">
              </el-table-column>
                <el-table-column prop="newsType.name" label="新闻类型" width="140">
                </el-table-column>
              <el-table-column prop="newsTitle" :show-overflow-tooltip="true" label="新闻标题" width="200">
              </el-table-column>
              <el-table-column prop="releaseTime" label="发布时间" width="200" :formatter="releaseTimeFormatter">
              </el-table-column>
              <el-table-column prop="releaseUser" label="发布人" width="200" :formatter="releaseUserFormatter">
              </el-table-column>
              <el-table-column prop="status" label="新闻状态" width="140" :formatter="statusFormatter">
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" width="250">
                <template slot-scope="scope">
                  <el-button size="mini" type="success" round
                             @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" round
                             @click="deleteEquipById(scope.$index, scope.row)">删除</el-button>
                  <el-button size="mini" v-if="scope.row.status == 0 && scope.row.istop == 0" type="primary" round
                             @click="isTop(1, scope.row)">推荐</el-button>
                  <el-button size="mini" v-if="scope.row.status == 0 && scope.row.istop == 1" type="primary" round
                             @click="isTop(0, scope.row)">撤回推荐</el-button>

                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </el-col>
    </el-row>
    <!-- 底部按钮和分页 -->
    <el-row :gutter="20" v-if="dataCount" type="flex" justify="space-between" align="center" class="page-wrapper">
      <el-col :span="24">
        <div class="page-item">
          <el-pagination background
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page.sync="listQuery.currentPage"
                         :page-sizes="pageSizes"
                         :page-size="listQuery.pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="dataCount"/>
        </div>
      </el-col>
    </el-row>

    <!-- 新增弹窗 -->
    <el-dialog title="新增新闻" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻类型" :label-width="formLabelWidth" prop="newsType">
              <el-select v-model="form.newsType" clearable placeholder="请选择新闻类型" class="filter-item">
                  <el-option v-for="item in newsTypeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻编号" :label-width="formLabelWidth" prop="newsNum">
              <el-input v-model="form.newsNum" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻标题" :label-width="formLabelWidth" prop="newsTitle">
              <el-input v-model="form.newsTitle" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻链接地址" :label-width="formLabelWidth" prop="newsUrl">
              <el-input v-model="form.newsUrl" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻内容" :label-width="formLabelWidth" prop="newsContents">
              <el-input type="textarea" v-model="form.newsContents" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="resetForm('form')">重 置</el-button>
        <el-button size="medium" type="success" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!--编辑  -->
    <el-dialog title="新闻信息编辑" :visible.sync="dialogFormVisible1">
      <el-form :model="oneCol" v-if="oneCol" :rules="rules" ref="oneCol">
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻类型" :label-width="formLabelWidth" prop="newsType">
              <el-select v-model="oneCol.newsType" clearable placeholder="请选择新闻类型" class="filter-item">
                  <el-option v-for="item in newsTypeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻编号" :label-width="formLabelWidth" prop="newsNum">
              <el-input v-model="oneCol.newsNum" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻标题" :label-width="formLabelWidth" prop="newsTitle">
              <el-input v-model="oneCol.newsTitle" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻链接地址" :label-width="formLabelWidth" prop="newsUrl">
              <el-input v-model="oneCol.newsUrl" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="20">
            <el-form-item label="新闻内容" :label-width="formLabelWidth" prop="newsContents">
              <el-input type="textarea" v-model="oneCol.newsContents" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="updateRiverNews('oneCol')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    export default {
        data(){
            return {
                //新闻类型下拉值
                newsTypeOptions:[],
                tableData:null,
                loading:false,
                multipleSelection: [],
                //默认数据总数
                dataCount:0,
                pageSizes:[5, 10, 20, 30, 40],
                //查询条件
                listQuery: {
                    currentPage:1,
                    pageSize:5,
                    releaseTime:[]
                },
                formLabelWidth: '120px',
                dialogFormVisible:false,
                dialogFormVisible1:false,
                //声明的一个单行表格数据
                oneCol:{},
                form: {},
                rules: {
                    newsType:[
                        { required: true, message: '请选择新闻类型', trigger: 'change' }
                    ],
                    newsNum:[
                        { required: true, message: '请输入新闻编号', trigger: 'blur' }
                    ],
                    newsTitle:[
                        { required: true, message: '请输入新闻标题', trigger: 'blur' }
                    ],
                    newsUrl:[
                        { required: true, message: '请输入新闻链接地址', trigger: 'blur' }
                    ],
                    newsContents:[
                        { required: true, message: '请输入新闻内容', trigger: 'blur' }
                    ]
                },
                pickerOptions2: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                }
            }
        },
        created() {
            this.getList();
            this.getNewsTypeOptions();
        },
        methods:{
            getList() {
                this.loading=true;
                this.postRequest('/api/rcs/riverNewss',this.listQuery).then((res)=>{
                    var data = res.data;
                    if(data.status == 200){
                        this.tableData=data.data
                        this.dataCount=data.count;
                        this.loading = false;
                    }else{
                        this.$message.error(data.msg);
                    }
                })
                    .catch((error)=>{
                        //错误信息
                        this.$message.error(error)
                    })
            },
            //获取新闻类型字典值
            getNewsTypeOptions(){
              this.getDictionary({types:["NEWS_TYPE"]}).then(res => {
                    var data = res.data;
                    if(data.status == 200){
                      this.newsTypeOptions = data.data["NEWS_TYPE"];
                    }else{
                        this.$message.error(data.msg);
                    }
                  })
                  .catch((error)=>{
                      this.$message.error(error)
                  })
            },
            //为空判断
            releaseTimeFormatter(row, column){
              return row.releaseTime ? row.releaseTime:"-";
            },
            releaseUserFormatter(row, column){
                return row.releaseUser ? row.releaseUser:"-";
            },
            statusFormatter(row, column){
              if(row.status === 0){
                  return "审批通过";
              }
              if(row.status === 8){
                  return "审批未通过";
              }
              if(row.status === 9){
                  return "审批中";
              }
              if(row.status === -1){
                  return "未提交";
              }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            indexMethod(index) {
                return (index+1)+(this.listQuery.currentPage-1)*this.listQuery.pageSize;
            },
            handleSizeChange(size) {
                this.listQuery.pageSize=size;
                this.listQuery.currentPage=1;
                this.getList()
            },
            handleCurrentChange(currentPage) {
                this.listQuery.currentPage=currentPage;
                this.getList()
            },
            //编辑操作
            handleEdit(index, row){
                let rowData = Object.assign({},row);
                this.oneCol=rowData;
                this.oneCol.newsType = rowData.newsType.code;
                this.dialogFormVisible1=true;
            },
            updateRiverNews(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.putRequest("/api/rcs/riverNews",this.oneCol).then((res)=>{
                            if(res.data.status == 200){
                                this.dialogFormVisible1 = false;
                                this.$message({
                                    message: '修改新闻信息成功！',
                                    type: 'success'
                                });
                                this.oneCol = {};
                                this.getList()
                            }else{
                                this.$message.error("修改新闻信息失败！");
                            }
                        })
                        .catch((error)=>{
                            //错误信息
                            this.$message.error(error)
                        })
                    }
                    else {
                            this.$message.error('error submit!!');
                            return false;
                        }
                    })
            },
            //是否推荐
            isTop(val,row){
                var istop;
                if(val == 1){
                    istop = 1;
                    this.$confirm("确认设置为推荐？").then(_ => {
                        this.putRequest("/api/rcs/riverNews", {"istop": istop, "id": row.id}).then((res) => {
                            if (res.data.status == 200) {
                                this.$message.success('设置为推荐成功！');
                                this.getList()
                            } else {
                                this.$message.error("设置为推荐失败！");
                            }
                        })
                            .catch((error) => {
                                //错误信息
                                this.$message.error(error)
                            })
                    })
                }else{
                    istop = 0;
                    this.$confirm("确认撤回推荐？").then(_ => {
                        this.putRequest("/api/rcs/riverNews", {"istop": istop, "id": row.id}).then((res) => {
                            if (res.data.status == 200) {
                                this.$message.success('撤回推荐成功！');
                                this.getList()
                            } else {
                                this.$message.error("撤回推荐失败！");
                            }
                        })
                            .catch((error) => {
                                //错误信息
                                this.$message.error(error)
                            })
                    })
                }

            },
            //删除单条
            deleteEquipById(index,row){
                this.$confirm("确认删除？").then(_ => {
                    this.putRequest("/api/rcs/riverNews",{"state":"-1","id":row.id}).then((res)=>{
                        if(res.data.status == 200){
                            this.$message.success('删除成功！');
                            this.getList()
                        }else{
                            this.$message.error("删除失败！");
                        }
                    })
                    .catch((error)=>{
                        this.$message.error(error)
                    })
                })
            },
            //批量操作
            batchEdit(val) {
                if(this.multipleSelection.length <= 0){
                    this.$message.warning('请至少选择一条数据！');
                    return;
                }
                var strArr = [];
                for (var i = 0; i < this.multipleSelection.length; i++) {
                    strArr.push(this.multipleSelection[i].id);
                }
                //前面三个参数分别是 表名，状态字段名，id字段名
                //status 为状态值 （0：正常  9：停用 -1：删除）
                //ids 为需要批量操作的 id数组
                var submitData = {
                    tableName: "river_news",
                    tableCol: "state",
                    tableId: "id",
                    status: val,
                    ids: strArr
                };

                this.$confirm("确认批量操作？").then(_ => {
                    this.putRequest("/api/common/batch", submitData)
                        .then(res => {
                            var data = res.data;
                            if (data.status == 200) {
                                this.$message.success(data.msg);
                                this.getList();
                            } else {
                                this.$message.error(data.msg);
                            }
                        })
                        .catch(error => {
                            //错误信息
                            this.$message.error(error);
                        });
                });
            },
            //新增
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.postRequest("/api/rcs/riverNews",this.form).then((res)=>{
                            if(res.data.status == 200){
                                this.dialogFormVisible = false;
                                this.$message.success('新增成功！');
                                this.form = {};
                                this.setConditionToNull();
                                this.getList();
                            }else{
                                this.$message.error("新增失败！");
                            }
                        })
                            .catch((error)=>{
                                //错误信息
                                this.$message.error(error);
                            })
                    } else {
                        this.$message.error('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //把条件查询置为空
            setConditionToNull(){
                this.listQuery.newsTitle = null;
                this.listQuery.status = null;
                this.listQuery.releaseTime = null;
            }

        },
        mounted(){},
        updated(){},
        destroyed(){},
    }
</script>
<style scoped>

</style>